package com.atguigu.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Author luliang
 * @Date 2019-12-02 17:47
 */
public class JmsConsumer {
    public static final String ACTIVEMQ_URL = "tcp://luliang888.top:61616";
    public static final String QNEUE_NAME = "queue01";

    public static void main(String[] args) throws Exception{
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QNEUE_NAME);
        MessageConsumer messageConsumer = session.createConsumer(queue);
/*        while (true) {
           //1. receive：同步阻塞方法     receive()：死等、阻塞  receive(long var1)：过时不候
            TextMessage message = (TextMessage)messageConsumer.receive();
            if (null != message) {
                System.out.println("***消费者接受的消息：" + message.getText());
            }else {
                break;
            }
        }*/

        //2. messageListener：通过监听的方式来消费消息
        messageConsumer.setMessageListener((message) -> {
            if (message != null && message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("***消费者接受的消息：" + textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        System.in.read();
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("消息接受完毕");
    }
}
